/*
 * 
 * v1.2 by tonydon
 */
package cn.txdnet.txweb.mail;

import cn.txdnet.txweb.utils.JsonUtil;
import cn.txdnet.txweb.utils.WebUtil;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import txdnet.util.DataUtil;
import txdnet.util.Logger;
import txdnet.util.StaticMark;
import txdnet.util.mail.SmtpParam;

/**
 * 用于加载多个SMTP发信账户并初始化设置
 * @author txdnet
 */
public class EmailConfig {
    
    private final static String MAIL_CONF_FILE = "mail-conf.js";
    private static List<SmtpParam> smtpAuthList = new ArrayList<SmtpParam>(2);
    private static int authNum = 0;
    
    /*
     * 加载 smtp mail 配置信息
     */
    public static void  initSmtpMailConf(){
        String mail_conf;
        try{
           List<SmtpParam> list;
           mail_conf = IOUtils.toString(EmailConfig.class.getResourceAsStream(StaticMark.STR_SLASH.concat(MAIL_CONF_FILE))).trim();
           // 清理注释:
           mail_conf = WebUtil.clearNote(mail_conf);
           if(mail_conf.length()<9){
               throw new RuntimeException(EmailConfig.class.getCanonicalName().concat(".initSmtpMailConf() - Not Config The Parameter Of Smtp Mail. ")); 
           }
           
           list = JsonUtil.parseArray(mail_conf, SmtpParam.class);
           for(SmtpParam sp : list){
               // 调用SmtpParam配置Smtp属性
               sp.initConfig();
           }
           smtpAuthList.addAll(list);
           authNum = smtpAuthList.size();
           Logger.info(EmailConfig.class, " Init Smtp Config - OK. Smtp Auth Pool Number:".concat(Integer.toString(authNum)));
        }catch(Exception ex){
            Logger.error(EmailConfig.class, ex.toString());
        }
    }
    
    public static SmtpParam getRandomSmtpParam(){
        return smtpAuthList.get(DataUtil.getRndInt(0, authNum));
    }
    
    public static SmtpParam getSmtpParam(int index){
        return smtpAuthList.get(index);
    }
    
    /**
     * 销毁对象
     */
    public static void destroy(){
        smtpAuthList.clear();
        smtpAuthList = null;
    }
}
